package com.wt.struggle.goodbye.main.adapter

import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.drawable.Drawable
import android.location.Location
import android.os.Bundle
import android.support.v4.util.LruCache
import android.support.v7.widget.RecyclerView
import android.util.Log
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import com.wt.struggle.goodbye.R
import com.wt.struggle.goodbye.base.Config
import com.wt.struggle.goodbye.base.ProActivity
import com.wt.struggle.goodbye.base.ProBaseAdapter
import com.wt.struggle.goodbye.base.Share
import com.wt.struggle.goodbye.info.NewsInfo
import com.wt.struggle.goodbye.user.activity.LoginActivity
import com.xin.lv.yang.utils.utils.DataUtil
import com.xin.lv.yang.utils.utils.ImageUtil
import kotlinx.android.synthetic.main.main_shop_item.view.*
import android.widget.ImageView
import com.bumptech.glide.Glide
import com.xin.lv.yang.utils.photo.image.AlbumBitmapCacheHelper


class TuiShopAdapter(context: Context, list: ArrayList<NewsInfo>) : ProBaseAdapter<NewsInfo>(context, list) {

    var cache: LruCache<String, Bitmap>? = null

    init {

        cache = object : LruCache<String, Bitmap>(getMemoryCacheSize()) {
            override fun sizeOf(key: String?, value: Bitmap?): Int {
                return value!!.byteCount / 1024
            }
        }

    }

    fun getMemoryCacheSize(): Int = (Runtime.getRuntime().maxMemory() / 8 / 1024).toInt()


    var code = 1
    var location: Location? = null

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        val vh = holder as VH
        val info = list[position]

        show(vh, info)

    }

    override fun getItemId(position: Int): Long {
        return position.toLong()
    }


    /**
     * 全局显示
     */
    fun show(vh: VH, info: NewsInfo) {

        showPicOrVideo(vh, info)

        showUserInfo(vh, info)

        showData(vh, info)
        initClick(vh, info)
    }


    /**
     * 点击事件
     */
    private fun initClick(vh: TuiShopAdapter.VH, info: NewsInfo) {

        vh.imageMainCollect.setOnClickListener {
            if (Share.getId(context) != 0) {
                if (onCollect != null) {
                    onCollect!!.onCollect(vh.adapterPosition)
                }
            } else {
                (context as ProActivity).showToastShort("请登录")
                context.startActivity(Intent(context, LoginActivity::class.java))
            }

        }

    }

    /**
     * 显示内容信息
     */
    private fun showData(vh: TuiShopAdapter.VH, info: NewsInfo) {
        if (info.isCollection == 1) {
            vh.imageMainCollect.setImageBitmap(BitmapFactory.decodeResource(context.resources, R.drawable.coll_y))
            vh.hotTvUserZan.setTextColor(context.resources.getColor(R.color.red))
        } else {
            vh.imageMainCollect.setImageBitmap(BitmapFactory.decodeResource(context.resources, R.drawable.coll_n))
            vh.hotTvUserZan.setTextColor(context.resources.getColor(R.color.black))
        }

        vh.hotTvUserZan.text = info.collectionCount.toString()


        if (code == 2) {

            vh.hotShopIndex.visibility = View.VISIBLE
            val dis = info.distance.toFloat()

            if (dis != 0f) {

                when {
                    dis > 1 -> vh.hotShopIndex.text = " ${dis.toInt()} km"
                    dis < 1 -> vh.hotShopIndex.text = " < 1km"
                    else -> vh.hotShopIndex.text = " 1km"
                }

            } else {

                if (location != null && info.lat != null && info.lat != "0" && info.lng != null && info.lng != "0") {

                    val mm =
                        DataUtil.gps2m(
                            location!!.latitude,
                            location!!.longitude,
                            info.lat.toDouble(),
                            info.lng.toDouble()
                        )

                    when {
                        mm > 1 -> vh.hotShopIndex.text = " ${mm.toInt()} km"
                        mm < 1 -> vh.hotShopIndex.text = " < 1km"
                        else -> vh.hotShopIndex.text = " 1km"
                    }
                } else {
                    vh.hotShopIndex.text = ""
                }
            }

        } else {
            vh.hotShopIndex.visibility = View.GONE
        }

        vh.hotShopName.setTextColor(context.resources.getColor(R.color.black))
        vh.hotShopName.text = DataUtil.getEmoji(context, info.content)

    }

    /**
     * 显示用户信息
     */
    private fun showUserInfo(vh: TuiShopAdapter.VH, info: NewsInfo) {
        val userInfo = info.userExtraInfo

        if (userInfo != null) {
            vh.hotUserName.text = userInfo.nickName
            ImageUtil.getInstance()
                .loadCircleCropImage(
                    context,
                    vh.hotUserImageHead,
                    Config.GET_IMAGE_URL + userInfo.avatar,
                    R.mipmap.logo_small
                )
        }

    }

    /**
     * 显示图片或者视频
     */
    private fun showPicOrVideo(vh: TuiShopAdapter.VH, info: NewsInfo) {

        vh.shopImageView.visibility = View.INVISIBLE

        val picList = info.picList

        val scanW = (getW(context) - context.resources.getDimension(R.dimen.dp_16).toInt()) / 2

        val hhh = if (vh.adapterPosition % 2 == 0) {

            scanW

        } else {
            (scanW * 1.04).toInt()
        }

        Log.i("result", "wwww------$scanW---hhhh------$hhh")

        vh.shopImageView.layoutParams = FrameLayout.LayoutParams(scanW, hhh)

        when {
            /// 显示单图片
            picList != null && picList.size != 0 -> {

                vh.shopImageVideo.visibility = View.INVISIBLE

                val videoInfoPic = picList[0]

                if (videoInfoPic != null) {

                    Log.i("result", "---------" + videoInfoPic.id)

                    val imageUrl = Config.GET_IMAGE_URL + videoInfoPic.id

                    val bbb = cache!![imageUrl]

                    if (bbb != null) {

                        vh.shopImageView.visibility = View.VISIBLE

                        vh.shopImageView.setImageBitmap(bbb)

                    } else {
                        ImageUtil.getInstance().loadByRoundBitmap(
                            context,
                            imageUrl,
                            0,
                            4,
                            scanW,
                            hhh
                        ) { image, bitmap ->

                            vh.shopImageView.visibility = View.VISIBLE

                            vh.shopImageView.setImageBitmap(bitmap)
                            cache!!.put(image, bitmap)
                        }
                    }
                }
            }

            /// 显示视频
            info.videoList != null && info.videoList!!.size != 0 -> {

                vh.shopImageVideo.visibility = View.VISIBLE

                vh.shopImageVideo.setImageBitmap(
                    BitmapFactory.decodeResource(
                        context.resources,
                        com.wt.struggle.goodbye.R.drawable.feed_more_video_icon
                    )
                )

                val arr = info.videoList

                if (arr != null && arr.size != 0) {

                    val video = arr[0]

                    val videoPath = video.domainname + if (video.path.startsWith("/")) {
                        video.path.subSequence(1, video.path.length)
                    } else {
                        video.path
                    }

                    vh.shopImageView.tag = videoPath

                    val bbb = cache!![videoPath]

                    if (bbb != null) {

                        vh.shopImageView.visibility = View.VISIBLE

                        vh.shopImageView.setImageBitmap(bbb)

                    } else {
                        ImageUtil.getInstance().loadVideoScreenshot(
                            context,
                            videoPath,
                            0) { imageUrl, bitmap ->

                            vh.shopImageView.visibility = View.VISIBLE

                            if (bitmap != null) {

                                vh.shopImageView.setImageBitmap(bitmap)
                                cache!!.put(videoPath, bitmap)

                            }
                        }
                    }
                }
            }


//            /// 显示音频
//            info.audioList != null && info.audioList!!.size != 0 -> {
//
//                vh.shopImageVideo.visibility = View.VISIBLE
//
//                vh.shopImageVideo.setImageBitmap(
//                    BitmapFactory.decodeResource(
//                        context.resources,
//                        R.drawable.play_voice
//                    )
//                )
//
//                if (picList != null && picList.size != 0) {
//
//                    val videoInfoPic = picList[0]
//
//                    val imageUrl = if (videoInfoPic.domainname != null && videoInfoPic.domainname != "") {
//                        val path = videoInfoPic.pathThumb
//                        videoInfoPic.domainname + if (path.startsWith("/")) {
//                            path.substring(1, path.length)
//                        } else {
//                            path
//                        }
//                    } else {
//                        Config.IMAGE_IP + videoInfoPic.pathThumb
//                    }
//
//                    ImageUtil.getInstance().loadRoundCircleImage(context, vh.shopImageView, imageUrl, 0, 4, scanW, hhh)
//
//                } else {
//                    vh.shopImageView.setImageBitmap(BitmapFactory.decodeResource(context.resources, R.drawable.pic5))
//                }
//
//            }
//

        }

    }


    override fun onCreateView(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        val view = inflater.inflate(R.layout.main_shop_item, parent, false)
        return VH(view)

    }

    override fun onUpdateHolder(holder: RecyclerView.ViewHolder, position: Int, payloads: MutableList<Any>) {
        val bundle = payloads[0] as Bundle
        val keySet = bundle.keySet()

        val vh = holder as VH

        for (key in keySet) {
            when (key) {
                "newInfo" -> {
                    val info = bundle.getParcelable(key) as NewsInfo

                    show(holder as VH, info)

                }
                "isCollection" -> {
                    val coll = bundle.getInt(key)
                    if (coll == 1) {
                        vh.imageMainCollect.setImageBitmap(
                            BitmapFactory.decodeResource(
                                context.resources,
                                R.drawable.coll_y
                            )
                        )
                        vh.hotTvUserZan.setTextColor(context.resources.getColor(R.color.red))
                    } else {
                        vh.imageMainCollect.setImageBitmap(
                            BitmapFactory.decodeResource(
                                context.resources,
                                R.drawable.coll_n
                            )
                        )
                        vh.hotTvUserZan.setTextColor(context.resources.getColor(R.color.black))
                    }

                }
                "collNum" -> {
                    val count = bundle.getInt(key)
                    vh.hotTvUserZan.text = count.toString()
                }
            }
        }

    }

    override fun onViewRecycled(holder: RecyclerView.ViewHolder) {
        super.onViewRecycled(holder)

    }


    /**
     * 在尾部添加
     */
    fun updateIn(arr: ArrayList<NewsInfo>) {

        for (temp in arr) {

            list.add(temp)

            notifyItemInserted(list.size)
        }
    }


    inner class VH(view: View) : RecyclerView.ViewHolder(view) {
        val shopImageView = view.shopImageView
        val hotShopName = view.hotShopName
        val hotUserImageHead = view.hotUserImageHead
        val hotUserName = view.hotUserName
        val imageMainCollect = view.imageMainCollect
        val hotTvUserZan = view.hotTvUserZan
        val hotShopIndex = view.hotShopIndex
        val shopImageVideo = view.shopImageVideo
        val itemLinearLayout = view.itemLinearLayout

    }

    var onCollect: OnCollectListener? = null

    interface OnCollectListener {
        fun onCollect(position: Int)
    }


}